/**
 * Copyright 2012 ibiblio
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.ibiblio.terasaur.bt

import org.ibiblio.terasaur.item.Item
import org.springframework.web.multipart.MultipartHttpServletRequest
import org.ibiblio.terasaur.ui.UrlHelper
import org.ibiblio.terasaur.bt.TorrentServiceAddCommand
import org.springframework.security.access.prepost.PreAuthorize
import org.ibiblio.terasaur.bencode.ByteArray

class TorrentService {
    static transactional = false
    def grailsApplication // injected
    def searchService // injected
    protected TorrentFileManager _torrentFileManager = null
    boolean _flushTransactions = false // Option for unit testing
    static UrlHelper urlHelper = new UrlHelper()

    @PreAuthorize("hasRole('ROLE_ADMIN') or hasPermission(#item, write)")
    public Map add(Item item, request) {
        def command = new TorrentServiceAddCommand([service: this, item: item, request: request])
        return command.run()
    }

    @PreAuthorize("hasRole('ROLE_ADMIN') or hasPermission(#item, write)")
    public Map delete(Item item, Torrent torrent) {
        def command = new TorrentServiceDeleteCommand([service: this, item: item, torrent: torrent])
        return command.run()
    }

    /**
     * Service method for use by other parts of the application.  Be sure to perform
     * appropriate permission checks
     */
    public ByteArray getTorrentFileContents(String infoHash) {
        TorrentFileManager fm = _getTorrentFileManager()
        return fm.getTorrentFileContents(infoHash)
    }

    protected TorrentFileManager _getTorrentFileManager() {
        String torrentRoot = grailsApplication.config.terasaur.torrent.root
        if (_torrentFileManager == null) {
            _torrentFileManager = new TorrentFileManager(torrentRoot)
        }
        return _torrentFileManager
    }
}
